import { Placeholder } from '@angular/compiler/src/i18n/i18n_ast';
import { Component, OnInit, ViewChild } from '@angular/core';
import { apiConf } from '@conf/api.conf';
import { cacheConf } from '@conf/cache.conf';
import { SFUISchema, SFSchema, SFUploadWidgetSchema, SFComponent, SFSelectWidgetSchema, SFTextWidgetSchema, SFSchemaEnum } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { EACacheService, EAEnvironmentService } from '@shared';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { VehicleService } from '../../../services/vehicle.service';

@Component({
  selector: 'app-car-carauth',
  templateUrl: './carauth.component.html',
  styleUrls: ['./carauth.component.less']
})
export class CarSettleCarauthComponent implements OnInit {
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('aaa', { static: false }) aaa!: any;
  record: any = {};
  i: any;
  ui: SFUISchema = {};
  schema: SFSchema = {};
  showCardFlag = false;
  showJopFlag = false;
  companyData: any = {};
  detailData: any = {};
  carNo = '';
  private titles = `
  根据监管要求：总质量 4.5 吨及以下普通货 运车辆的，可填车籍地 6 位行政区域代码+000000。
  `;
  constructor(
    private modal: NzModalRef,
    public service: VehicleService,
    private envSrv: EAEnvironmentService,
    private eaCacheSrv: EACacheService
  ) { }

  ngOnInit(): void {
    this.initData();
    this.initSF();
  }
  initData() {
    if (this.i.id) {
      this.companyData = this.eaCacheSrv.get(cacheConf.env);
      const params = {
        id: this.i.id
      };
      this.service.request(this.service.$api_shipperCarGet, params).subscribe(res => {
        this.detailData = res;
        this.detailData.isSelf = res.isSelf ? 1 : 0;
        this.detailData.isTrailer = res.isTrailer ? 1 : 0;
        this.detailData.carFrontPhotoWatermark = [
          {
            uid: -1,
            name: 'LOGO',
            status: 'done',
            url: this.detailData.carFrontPhotoWatermark,
            response: this.detailData.carFrontPhotoWatermark
          }
        ];
        this.detailData.carProtocalWatermark = [
          {
            uid: -1,
            name: 'LOGO',
            status: 'done',
            url: this.detailData.carProtocalWatermark,
            response: this.detailData.carProtocalWatermark
          }
        ];
        this.detailData.certificatePhotoFrontWatermark = [
          {
            uid: -1,
            name: 'LOGO',
            status: 'done',
            url: this.detailData.certificatePhotoFrontWatermark,
            response: this.detailData.certificatePhotoFrontWatermark
          }
        ];
        this.detailData.certificatePhotoBackWatermark = [
          {
            uid: -1,
            name: 'LOGO',
            status: 'done',
            url: this.detailData.certificatePhotoBackWatermark,
            response: this.detailData.certificatePhotoBackWatermark
          }
        ];
        this.detailData.roadTransportPhotoWatermark = [
          {
            uid: -1,
            name: 'LOGO',
            status: 'done',
            url: this.detailData.roadTransportPhotoWatermark,
            response: this.detailData.roadTransportPhotoWatermark
          }
        ];
      });
    }
  }
  initSF() {
    this.schema = {
      properties: {
        carFrontPhotoWatermark: {
          type: 'string',
          title: '车头照照片',
          ui: {
            action: apiConf.waterFileUpload,
            accept: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            widget: 'upload',
            descriptionI18n: '请上传车头照照片，支持JPG、PNG格式，文件小于5M。',
            data: {
              appId: this.envSrv.env.appId
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                console.log(args);
                const avatar = [
                  {
                    uid: -1,
                    name: 'LOGO',
                    status: 'done',
                    url: args.file.response.data.fullFileWatermarkPath,
                    response: {
                      url: args.file.response.data.fullFileWatermarkPath
                    }
                  }
                ];
                this.sf?.setValue('/carFrontPhotoWatermark', avatar);
                this.detailData.carFrontPhoto = args.file.response.data.fullFilePath;
                this.checkCarCard(args.file.response.data.fullFilePath, 'back');
              }
            },
            beforeUpload: (file: any, _fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isLt2M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                console.log(_fileList);

                observer.next(isLt2M);
                observer.complete();
              });
            }
            // previewFile: (file: NzUploadFile) => of(
            //   file?.response?.data?.fullFilePath
            //   ),
          }
        },
        carNo: {
          title: '车牌号',
          maxLength: 9,
          type: 'string',
          ui: {
            placeholder: '请输入'
          }
        },
        carNoColor: {
          title: '车牌颜色',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'car:color' },
            placeholder: '请选择车牌颜色',
            containsAllLabel: false
          } as SFSelectWidgetSchema
        },
        carModel: {
          title: '车型',
          type: 'string',
          readOnly: true,
          ui: {
            placeholder: '请上传行驶证自动带出'
          }
        },
        carEnergyType: {
          title: '车辆能源类型',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'car:energy:type' },
            placeholder: '请选择车辆能源类型',
            containsAllLabel: false
          }
        },
        carLength: {
          title: '车长',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'car:length' },
            placeholder: '请选择车长',
            containsAllLabel: false
          } as SFSelectWidgetSchema
        },
        carLoad: {
          title: '核定载质量',
          type: 'string',
          maxLength: 6,
          ui: {
            placeholder: '请输入',
            addOnAfter: '吨',
            change: (val: any) => {
              const value = val.replace(/\D/g, '');
              this.sf.setValue('/carLoad', value);
            }
          }
        },
        isSelf: {
          title: '是否挂靠',
          type: 'string',
          enum: [
            { label: '否', value: 0 },
            { label: '是', value: 1 }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        isTrailer: {
          title: '是否为挂车',
          type: 'string',
          enum: [
            { label: '否', value: 0 },
            { label: '是', value: 1 }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        carProtocalWatermark: {
          type: 'string',
          title: '挂靠协议',
          ui: {
            action: apiConf.waterFileUpload,
            accept: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            widget: 'upload',
            descriptionI18n: '请上传挂靠协议，支持JPG、PNG格式，文件小于5M。',
            data: {
              appId: this.envSrv.env.appId
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                const avatar = [
                  {
                    uid: -1,
                    name: 'LOGO',
                    status: 'done',
                    url: args.file.response.data.fullFileWatermarkPath,
                    response: {
                      url: args.file.response.data.fullFileWatermarkPath
                    }
                  }
                ];
                this.sf?.setValue('/carProtocalWatermark', avatar);
                this.detailData.certificatePhotoFront = args.file.response.data.fullFilePath;
              }
            },
            beforeUpload: (file: any, _fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  this.service.msgSrv.warning('图片大小超过2M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt2M);
                observer.complete();
              });
            },
            previewFile: (file: NzUploadFile) => of(file.url)
          }
        },
        agreeImg: {
          title: '',
          type: 'boolean',
          // enum: [{ label: '长期', value: true }],
          ui: {
            widget: 'custom'
          }
        },
        driverId: {
          type: 'string',
          title: '挂靠司机',
          ui: {
            widget: 'select',
            placeholder: '输入司机手机号进行联想',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => {
              const param = { mobiles: q };
              return this.service
                .request(this.service.$api_get_driver_by_mobile, param, 'POST', true, 'FORM')
                .pipe(
                  map(res =>
                    (res as any[]).map(
                      i =>
                        ({
                          label: `${i.userName}(${i.telephone})`,
                          value: i.appUserId
                        } as SFSchemaEnum)
                    )
                  )
                )
                .toPromise();
            },
            visibleIf: {
              isSelf: value => ( value == 1 )
            }
          } as SFSelectWidgetSchema
        },
        titleA: {
          title: '行驶证信息(必填）',
          type: 'string',
          ui: {
            widget: 'text'
          },
          default: '照片上传后会自动识别文字并填充下列内容栏'
        },
        tipsA: {
          title: '',
          type: 'string',
          ui: {
            widget: 'custom',
            offsetControl: 6
          }
        },
        certificatePhotoFrontWatermark: {
          type: 'string',
          title: '行驶证首页照片',
          ui: {
            action: apiConf.waterFileUpload,
            accept: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            widget: 'upload',
            descriptionI18n: '请上传行驶证首页照片，支持JPG、PNG格式，文件小于5M。照片信息缺失、拼凑、过度PS、模糊不清，都不会通过审核。',
            data: {
              appId: this.envSrv.env.appId
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                const avatar = [
                  {
                    uid: -1,
                    name: 'LOGO',
                    status: 'done',
                    url: args.file.response.data.fullFileWatermarkPath,
                    response: {
                      url: args.file.response.data.fullFileWatermarkPath
                    }
                  }
                ];
                this.sf?.setValue('/certificatePhotoFrontWatermark', avatar);
                this.detailData.certificatePhotoFront = args.file.response.data.fullFilePath;
                this.checkCarCard(args.file.response.data.fullFilePath, 'front');
              } else {
                this.detailData.certificatePhotoFront = '';
              }
            },
            beforeUpload: (file: any, _fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isLt2M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt2M);
                observer.complete();
              });
            }
            // previewFile: (file: NzUploadFile) => of(file.url),
          }
        },
        tipsB: {
          title: '',
          type: 'string',
          ui: {
            widget: 'custom',
            offsetControl: 6
          }
        },
        certificatePhotoBackWatermark: {
          type: 'string',
          title: '行驶证副页照片',
          ui: {
            action: apiConf.waterFileUpload,
            accept: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            widget: 'upload',
            descriptionI18n: '请上传行驶证副业照片，支持JPG、PNG格式，文件小于5M。',
            data: {
              appId: this.envSrv.env.appId
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                const avatar = [
                  {
                    uid: -1,
                    name: 'LOGO',
                    status: 'done',
                    url: args.file.response.data.fullFileWatermarkPath,
                    response: {
                      url: args.file.response.data.fullFileWatermarkPath
                    }
                  }
                ];
                this.sf?.setValue('/certificatePhotoBackWatermark', avatar);
                this.detailData.certificatePhotoBack = args.file.response.data.fullFilePath;
                this.checkCarCard(args.file.response.data.fullFilePath, 'back');
              } else {
                this.detailData.certificatePhotoBack = '';
              }
            },
            beforeUpload: (file: any, _fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isLt2M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt2M);
                observer.complete();
              });
            }
            // previewFile: (file: NzUploadFile) => of(file.url),
          }
        },
        driverLicenseRegisterTime: {
          title: '行驶证注册日期',
          type: 'string',
          format: 'date',
          ui: {
            placeholder: '请输入'
          }
        },
        driverLicenseGetTime: {
          title: '行驶证发证日期',
          type: 'string',
          format: 'date',
          ui: {
            placeholder: '请输入'
          }
        },
        driverLicenseEndTime: {
          title: '行驶证到期日期',
          type: 'string',
          format: 'date',
          maxLength: 30,
          ui: {
            placeholder: '请输入'
          }
        },
        driverLicenseSigningOrg: {
          title: '行驶证签发机关',
          type: 'string',
          maxLength: 30,
          ui: {
            placeholder: '请输入'
          }
        },
        carDistinguishCode: {
          title: '车辆识别代码',
          type: 'string',
          maxLength: 30,
          ui: {
            placeholder: '请输入'
          }
        },
        // useNature: {
        //   title: '使用性质',
        //   type: 'string',
        //   maxLength: 30,
        //   ui: {
        //     placeholder: '请输入'
        //   }
        // },
        useNature: {
          title: '使用性质',
          type: 'string',
          enum: [
            { label: '货运', value: '2' },
            { label: '营运', value: '1' },
            { label: '非营运', value: '0' },
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        curbWeight: {
          title: '整备质量',
          type: 'string',
          ui: {
            placeholder: '请输入',
            addOnAfter: '吨'
          }
        },
        carTotalLoad: {
          title: '总质量',
          type: 'string',
          ui: {
            addOnAfter: '吨',
            placeholder: '请输入'
          }
        },
        carOwner: {
          title: '所有人',
          type: 'string',
          maxLength: 30,
          ui: {
            placeholder: '请输入'
          }
        },
        titleB: {
          title: '道运证(选填）',
          type: 'string',
          ui: {
            widget: 'text'
          },
          default: '照片上传后会自动识别文字并填充下列内容栏'
        },
        roadTransportPhotoWatermark: {
          type: 'string',
          title: '道运证照片',
          ui: {
            action: apiConf.waterFileUpload,
            accept: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            widget: 'upload',
            descriptionI18n: '请上传道运证照片，支持JPG、PNG格式，文件小于5M。蓝牌绿牌车辆，可不用传道运证',
            data: {
              appId: this.envSrv.env.appId
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                const avatar = [
                  {
                    uid: -1,
                    name: 'LOGO',
                    status: 'done',
                    url: args.file.response.data.fullFileWatermarkPath,
                    response: {
                      url: args.file.response.data.fullFileWatermarkPath
                    }
                  }
                ];
                this.sf?.setValue('/roadTransportPhotoWatermark', avatar);
                this.detailData.roadTransportPhoto = args.file.response.data.fullFilePath;
                this.checkTransCard(args.file.response.data.fullFilePath);
              } else {
                this.detailData.roadTransportPhoto = '';
              }
            },
            beforeUpload: (file: any, _fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isLt2M) {
                  this.service.msgSrv.warning('图片大小超过5M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt2M);
                observer.complete();
              });
            }
            // previewFile: (file: NzUploadFile) => of(file.url),
          }
        },
        roadImg: {
          title: '',
          type: 'boolean',
          // enum: [{ label: '长期', value: true }],
          ui: {
            widget: 'custom'
          }
        },
        roadTransportNo: {
          title: '道运证号码',
          type: 'string',
          maxLength: 30,
          ui: {
            // widget: this.detailData.commitFlag !== 0 ? 'text' : '',
            placeholder: '请输入',
            optionalHelp: {
              i18n: this.titles
            }
          }
        },
        '': {
          type: 'number', ui: {
            widget: 'text',
            html: this.aaa,
            defaultText: '点击查看行政区域代码'
          } as SFTextWidgetSchema
        },
        roadTransportLicenceNo: {
          title: '经营许可证号',
          type: 'string',
          maxLength: 30,
          ui: {
            // widget: this.detailData.commitFlag !== 0 ? 'text' : '',
            placeholder: '请输入'
          }
        },
        roadTransportStartTime: {
          title: '发证日期',
          type: 'string',
          format: 'date',
          ui: {
            placeholder: '请输入'
          }
        },
        roadTransportEndTime: {
          title: '有效期至',
          type: 'string',
          format: 'date',
          ui: {
            placeholder: '请输入'
          }
        }
      },
      required: [
        'carFrontPhotoWatermark',
        'carNo',
        'carNoColor',
        'carModel',
        'carEnergyType',
        'carLength',
        'carLoad',
        'isSelf',
        'isTrailer',
        'certificatePhotoFrontWatermark',
        'certificatePhotoBackWatermark',
        'driverLicenseRegisterTime',
        'driverLicenseGetTime',
        'driverLicenseEndTime',
        'driverLicenseSigningOrg',
        'carDistinguishCode',
        'useNature',
        'curbWeight',
        'carTotalLoad',
        'carOwner'
      ]
    };

    this.ui = {
      '*': {
        spanLabelFixed: 180,
        grid: { span: 18 },
        width: 600
      },
      $title1: {
        spanLabelFixed: 0
      },
      $title2: {
        spanLabelFixed: 0
      },
      $title3: {
        spanLabelFixed: 0
      },
      $isTrailer: {
        grid: { span: 24 }
      },
      $carProtocalWatermark: {
        grid: { span: 12 }
      },
      $agreeImg: {
        grid: { span: 3 },
        class: 'setCustom'
      },
      $titleB: {
        grid: { span: 24 }
      },
      $roadTransportPhotoWatermark: {
        grid: { span: 12 }
      },
      $roadImg: {
        grid: { span: 4 },
        class: 'setCustom'
      }
    };
  }
  // 道路运输证识别
  checkTransCard(imgurl: any) {
    const params = {
      transportationLicenseUrl: imgurl
    };
    this.service.request(this.service.$api_recognizeTransportationLicense, params).subscribe((res: any) => {
      if (res) {
        this.sf.setValue('/roadTransportNo', res.number);
        this.sf.setValue('/roadTransportLicenceNo', res.businessCertificate);
        this.sf.setValue('/roadTransportStartTime', res.issueDate);
        if (this.carNo === '') {
          this.carNo = res.number;
        } else if (this.carNo && res.vehicleNumber.indexOf(this.carNo) === -1) {
          this.service.msgSrv.warning('请上传同一认证车辆的相关证件');
        }
      }
    });
  }
  // 行驶证识别
  checkCarCard(imgurl: any, side: any) {
    const params = {
      vehicleLicenseUrl: imgurl,
      side
    };
    this.service.request(this.service.$api_recognizeVehicleLicense, params).subscribe((res: any) => {
      if (res) {
        if (side === 'front') {
          // 正面
          this.sf.setValue('/driverLicenseRegisterTime', res.registerDate);
          this.sf.setValue('/carNo', res.number);
          this.sf.setValue('/driverLicenseGetTime', res.issueDate);
          this.sf.setValue('/driverLicenseSigningOrg', res.issuingAuthority);
          this.sf.setValue('/carDistinguishCode', res.vin);
          this.sf.setValue('/carOwner', res.name);
          this.sf.setValue('/useNature', res.useCharacter);
          this.sf.setValue('/carModel', res?.vehicleType);
          this.sf.setValue('/carTotalLoad', res?.grossMass.slice(0, -2) % 1000);
        } else {
          this.sf.setValue('/curbWeight', res.unladenMass.slice(0, -2) % 1000);
          this.sf.setValue('/carLoad', res.approvedLoad);
          // this.sf.setValue('/carLoad', res.approvedLoad.slice(0, -2) % 1000);
        }
        if (this.carNo === '') {
          this.carNo = res.number;
        } else if (this.carNo && this.carNo !== res.number) {
          this.service.msgSrv.warning('请上传同一认证车辆的相关证件');
        }
      }
    });
  }

  close(): void {
    this.modal.close(true);
  }
  showExample() {
    this.showCardFlag = !this.showCardFlag;
  }
  showJopExample() {
    this.showJopFlag = !this.showJopFlag;
  }
  submitForm() {
    const params: any = {
      appUserId: this.i.appUserId,
      ...this.sf?.value,
      bindType: this.i.bindType
    };
    params.carFrontPhoto = this.detailData.carFrontPhoto;
    params.carProtocal = this.detailData.carProtocal;
    params.certificatePhotoFront = this.detailData.certificatePhotoFront;
    params.certificatePhotoBack = this.detailData.certificatePhotoBack;
    params.roadTransportPhoto = this.detailData.roadTransportPhoto;
    delete params.titleA;
    delete params.titleB;
    console.log(params);

    this.service.request(this.service.$api_saveUpdateShipperCar, params).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('添加成功');
        this.modal.close(true);
      }
    });
  }
  view() {
    window.open('http://www.mca.gov.cn/article/sj/xzqh/1980/')
  }
}
